Simple C: atof giving wrong value [migrated]

Posted by Doc on Programmers See other posts from Programmers or by Doc
Published on 2012-03-25T17:27:43Z Indexed on 2012/03/25 23:40 UTC
Read the original article Hit count: 211

Filed under:

I have a program that reads input from a singe line(string obviously) and organizes it into arrays.

The problem I have is that at one point the program reads two different values and returns the first one twice. Initially I thought the program was reading the same value twice but when I tested it turned out that it got the correct one but is inputting the wrong one.

for example

Input: 2 0.90 0.75 0.7 0.65

sorry to snip it

(while(fgets (string[test], sizeof(string[test]),ifp))
pch = strtok_r(NULL, " ", &prog);
tem3 = atoi(pch);
while (loop<tem3)
{
    pch=strtok_r(NULL," ",&prog);
    venseatfloat[test][loop][DISCOUNT][OCCUPIED]=(float)atof(pch);
    printf("%f is discount\t",venseatfloat[test][loop][DISCOUNT][OCCUPIED]);

    pch=strtok_r(NULL, " ", &prog);
    strcpy(temp, pch);
    venseatfloat[test][loop][REGULAR][OCCUPIED]=(float)atof(pch);
    printf("%s is the string but %.3f is regular\n", temp ,venseatfloat[test][loop][DISCOUNT][OCCUPIED]);
    loop++;

}

output:

>0.900000 is discount    0.75 is the string but 0.900 is regular

>0.700000 is discount    0.65 is the string but 0.700 is regular

What is going on?

© Programmers or respective owner

Related posts about pointers